package com.nf.practice.downloadFile;

import cn.hutool.http.HttpUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

// 根据指定条件下载影像件
public class AccordingConditionDownloadImg4 {

    private static final int THREAD_POOL_SIZE = 20; // 线程池大小
    private static final int BUFFER_SIZE = 4096; // 缓冲区大小

    private final List<String> idNoDirs = Arrays.asList("B","B01","B02");
    private final List<String> loanContractDirs = Arrays.asList("AA05", "AB05", "AC02", "AE03", "AF01", "AG02", "AD02", "AH01", "AI02", "U04", "U11", "K");
    private final List<String> guaranteeContractDirs = Arrays.asList("S", "S03", "AE04", "AA07", "U15");

    // 指定目录
//    B 身份证
//    B01 本人身份证正面
//    B02 本人身份证反面
//    S03 担保服务合同
//    AE04 大秦担保服务合同
//    AA07 保福担保服务合同
//    U15 担保服务合同
    private final List<String> targetDir = Arrays.asList(
            "AA05",
            "AB05",
            "AC02",
            "AE03",
            "AF01",
            "AG02",
            "AD02",
            "AH01",
            "AI02",
            "U04",
            "U11",
            "K",
            "B",
            "B01",
            "B02",
            "S03",
            "AE04",
            "AA07",
            "U15"
    );


    // 借款合同目录集合
//    private final List<String> targetDir = Arrays.asList(
//            "AA05",
//            "AB05",
//            "AC02",
//            "AE03",
//            "AF01",
//            "AG02",
//            "AD02",
//            "AH01",
//            "AI02",
//            "U04",
//            "U11",
//            "K"
//    );

    // 借款目录+债转文件目录
//    private final List<String> targetDir = Arrays.asList(
//            "AA05",
//            "AB05",
//            "AC02",
//            "AE03",
//            "AF01",
//            "AG02",
//            "AD02",
//            "AH01",
//            "AI02",
//            "U04",
//            "U11",
//            "K",
//            "AE12",
//            "AF03"
//    );

    // 目录英转中
    private final Map<String, String> dirsEngToCh = new HashMap<String, String>() {
        {
            put("AA05", "新网借款合同");
            put("AB05", "苏宁额度借款合同");
            put("AC02", "华兴借款合同");
            put("AE03", "振兴借款合同");
            put("AF01", "中关村个人借款合同");
            put("AG02", "三湘个人借款合同");
            put("AD02", "借款合同");
            put("AH01", "借款合同");
            put("AI02", "华通借款合同");
            put("U04",  "一押借款/抵押合同");
            put("U11",  "借款合同");
            put("K",    "合同");
            put("AE12", "债转相关文件");
            put("AF03", "债转文件");
        }
    };

    // 1、根据单号下载影像件
    @Test
    public void accordingAppNoDownloadImg() {
        List<PicExportDetail> dataList = new ArrayList<>();
        // 影像件生产地址
        String picUrl = "http://192.168.40.78:8081";
//        List<String> appNoList = Arrays.asList(
//                "20200915150000190350",
//                "20200608160000131807",
//                "02202105201018009512",
//                "20201016090000204293"
//                "02202108160920454422"
//        );

        // 测试地址
//        String picUrl = "http://172.16.10.5:31312";
//        List<String> appNoList = Arrays.asList("01202312141557421008");

        String excelName = "E:/file/E类测试.xlsx";
//        String excelName = "E:/file/1228测试.xlsx";

        // 读取到的数据
        List<PicData> appNos = EasyExcel.read(excelName)
                .head(PicData.class)
                .sheet()
                .doReadSync();
        List<String> appNoList = appNos.stream().map(item -> item.getAppNo()).collect(Collectors.toList());

        Long begin = System.currentTimeMillis();
        ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
        List<Future<Boolean>> futures = new ArrayList<>();
        for (String appNo : appNoList) {
            Future<Boolean> future = executorService.submit(() -> {
                int idNoNum = 0;
                int loanContractNum = 0;
                int guaranteeContractNum = 0;
                PicExportDetail data = new PicExportDetail();

                Map<String, Object> reqMap = new HashMap<>();
                reqMap.put("appNo", appNo);
                // 根据appNo调用影像件系统获取影像件存放地址和目录
                String resJson = doPost(picUrl + "/file-system/picture/queryImgListAll", reqMap);
                JSONObject jsonData = JSONObject.parseObject(resJson);
                JSONArray resArr = jsonData.getJSONArray("data");
                String status = jsonData.getString("status");
                if (!"S".equals(status) || CollectionUtils.isEmpty(resArr)) {
                    data.setAppNo(appNo)
                            .setIdNoNum(String.valueOf(idNoNum))
                            .setLoanContractNum(String.valueOf(loanContractNum))
                            .setGuaranteeContractNum(String.valueOf(guaranteeContractNum));
                    dataList.add(data);
                } else {
                    List<JSONObject> list = JSONObject.parseArray(jsonData.getJSONArray("data").toJSONString(), JSONObject.class);
                    try {
                        // 遍历影像件并根据目录存放对应的文件到本地
                        for (int i = 0; i < list.size(); i++) {
                            // 文件地址
                            String fileUrl = list.get(i).getString("filePath");
                            // String appNo = list.get(i).getString("appNo");
                            // 文件名
                            String fileName = list.get(i).getString("fileName");
                            // 文件目录
                            String subclassSort = list.get(i).getString("subclassSort");
                            if (!targetDir.contains(subclassSort)) {
                                continue;
                            }
                            // 目录中文名
//                    String chDir = dirsEngToCh.get(subclassSort);
                            // 创建目录
//                    String directoryPath = "E:/file/" + appNo + "/" + chDir + "/";

                            String directoryPath = "C:/fileE3/" + appNo + "/";

                            File directory = new File(directoryPath);
                            // 如果目录不存在，则创建它
                            if (!directory.exists()) {
                                directory.mkdirs();
                            }
                            // 创建文件对象，使用fileName作为文件名
                            File file = new File(directory, fileName);
                            // 使用Hutool的HttpUtil工具类下载影像件文件,文件保存的关键步骤
                            HttpUtil.downloadFile(fileUrl, file);
                            System.out.println(appNo + "-" + "下载成功!");
                            if (idNoDirs.contains(subclassSort)) {
                                idNoNum++;
                            } else if (loanContractDirs.contains(subclassSort)) {
                                loanContractNum++;
                            } else if (guaranteeContractDirs.contains(subclassSort)) {
                                guaranteeContractNum++;
                            }
                        }

                        data.setAppNo(appNo)
                                .setIdNoNum(String.valueOf(idNoNum))
                                .setLoanContractNum(String.valueOf(loanContractNum))
                                .setGuaranteeContractNum(String.valueOf(guaranteeContractNum));
                        dataList.add(data);
                    } catch (Exception e) {
                        System.out.println(appNo + "-" + "下载异常!" + e.getMessage());
                    }
                }
                return true;
            });
            futures.add(future);
        }
        // 等待所有任务完成
        for (Future<Boolean> future : futures) {
            try {
                future.get(); // 这会阻塞，直到该future完成
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }

        ExcelWriter writer = ExcelUtil.getWriter(new File("C:/fileE3/E类测试.xlsx"));
        if(!CollectionUtils.isEmpty(dataList)){
            writer.setSheet(0).write(dataList);
            writer.flush();
        }
        System.out.println("下载结束,计算耗时：" + (System.currentTimeMillis() - begin) + "ms");
        executorService.shutdown(); // 关闭线程池
    }

    @Test
    public String doPost(String url, Object params) {
        String json = JSON.toJSONString(params);
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        String response = null;
        try {
            StringEntity s = new StringEntity(json);
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");//发送json数据需要设置contentType
            post.setEntity(s);
            HttpResponse res = client.execute(post);
            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                response = EntityUtils.toString(res.getEntity());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return response;
    }

    private final static String dmsUrl = "http://172.16.10.5:31314/service";

    @Test
    public void exportDataToExcel() {
        String tableName = "tbl_dsf_log";
        JSONObject req = new JSONObject();
        req.put("tableName", tableName);
        String resp = doPost(dmsUrl + "/getCacheData/getDataByTableName", req.toJSONString());
        JSONObject respJson = JSON.parseObject(resp);
        if(!"000000".equals(respJson.getString("code"))) {
            System.out.println("查询征信缓存数据异常:"+respJson.getString("code"));
        }
//        return respJson.getJSONArray("data");


    }


}
